package com.zxymq.amqp.listener;

import com.rabbitmq.client.Channel;
import com.zxymq.amqp.constants.MQConstants;
import com.zxymq.amqp.util.redis.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 死信队列消息监听，当有死信发生时会自动监听到
 *
 * @author:
 * @date :2018/1/11
 * {@link org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;}
 * {@link https://www.cnblogs.com/gordonkong/p/7201898.html}
 */
@Component
public class DeadLetterMessageListener implements ChannelAwareMessageListener {
    private Logger logger = LoggerFactory.getLogger(DeadLetterMessageListener.class);


    @Autowired
    private RedisUtils redisTemplate;
    //把死信队列数据入库，并邮件通知
	/*@Autowired
	private DeadLetterMessageMapper deadLetterMessageMapper;

	@Autowired
	private MailServiceImpl mailService;*/

    // 收件人
	/*@Value("${recipient.email.address}")
	private String emailRecipient;*/

    /**
     * 处理收到的rabbit消息的回调
     *
     * @author:
     * @date :2018/1/11
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        MessageProperties messageProperties = message.getMessageProperties();
        // 消息体
        String messageBody = new String(message.getBody());

        logger.warn("dead letter message：{} | tag：{}", messageBody, message.getMessageProperties().getDeliveryTag());
		/*// 入库
		insertRecord(logKey, message);
		// 发邮件
		sendEmail(logKey, messageProperties.getMessageId(), messageBody);*/
        //这里如果不手动确认ACK，那么就会存放在死信队列中,再次启动应用，会再次消费
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        redisTemplate.delMapField(MQConstants.MQ_PRODUCER_RETRY_KEY, messageProperties.getMessageId());
    }

    /**
     * 入库
     *//*
	private void insertRecord(String logKey, Message message) {
		try {
			MessageProperties msgProp = message.getMessageProperties();
			DeadLetterMessageVo entity = new DeadLetterMessageVo();
			entity.setId(Identity.asyncUUID());
			entity.setMsgId(msgProp.getMessageId());
			entity.setMsgBody(new String(message.getBody()));
			entity.setDeliverTag("" + msgProp.getDeliveryTag());
			// PRODUCER为生产,CONSUMER为消费
			entity.setType(StringUtil.isNotBlank(msgProp.getType()) ? msgProp.getType() : Constants.MQ_CONSUMER);
			deadLetterMessageMapper.insert(entity);
			logger.info("{}|死信入库, {}", logKey, entity.toString());
		} catch (Exception e) {
			logger.error("{}|死信入库发生异常,{}", logKey, e.getMessage());
		}
	}

	*//**
     * 发邮件
     *//*
	private void sendEmail(String logKey, String msgId, String msgBody) {
		try {
			String subject = "MQ处理异常";
			StringBuilder cnt = new StringBuilder();
			cnt.append("ID:" + msgId + "\n");
			cnt.append("消息体:" + msgBody + "\n");
			cnt.append("出现异常,请及时处理");
			mailService.sendSimpleMail(emailRecipient, subject, cnt.toString());
			logger.info("{}|发送邮件成功!", logKey);
		} catch (Exception e) {
			logger.error("{}|发送邮件----异常----", logKey, e.getMessage());
		}
	}*/
}
